package com.zerox.controller;

import com.alibaba.fastjson.JSON;
import com.zerox.domain.TableVO;
import com.zerox.pojo.SysUser;
import com.zerox.service.SysUserService;
import org.apache.commons.lang.math.RandomUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.validation.Valid;
import java.io.File;
import java.io.IOException;
import java.util.List;
import java.util.Map;

//
// @Component
// @Service  业务逻辑的Bean
// @Repository 数据访问Bean
// @Controller 控制器的Bean

@Controller
@RequestMapping("/user")
public class UserController {

    @Autowired
    private SysUserService sysUserService;

    @GetMapping("/tolist")
    public String toList(){
        return "list";
    }

    @GetMapping("/toadd")
    public String toAdd(){
        return "add";
    }

    @GetMapping("/toupdate/{id}")
    public String toUpdate(Model model,@PathVariable Integer id){
        SysUser sysUser = sysUserService.selectById(id);
        model.addAttribute("sysUser",sysUser);
        return "update";
    }

    @GetMapping("/accountExists")
    @ResponseBody
    public String accountExists(String account){
        SysUser sysUser = sysUserService.selectByAccount(account);
        if (sysUser==null){
            return "0";
        }
        return "1";
    }


    // @RequestMapping(value = "/list",method = RequestMethod.GET)
    @GetMapping(value = "/list",produces = {"application/json;charset=utf-8"})
    @ResponseBody
    public String list(Model model, Integer page, Integer limit,String realName,Integer roleId) throws IOException {

        List<SysUser> userList = sysUserService.list(page, limit,realName,roleId);
        /*
         *  {"code":0,"count":1000,"data":[userList],"msg":""}
         */
        int count = sysUserService.count(realName, roleId);
        TableVO tableVO = new TableVO(0, count, userList, "");

        String json = JSON.toJSONString(tableVO);

        // response.setContentType("application/json;charset=utf-8");
        // response.getWriter().print(json);

        return json;
    }


    @GetMapping("/list2")
    public String list2(Map<String,Object> map, @RequestParam(value = "ids",required = false,defaultValue = "0") Integer id){
        System.out.println(this);
        map.put("id",id);
        // 转发
        return "forward:tolist";
    }

    @GetMapping("/list1")
    public ModelAndView list1(@RequestParam(value = "ids",required = false,defaultValue = "0") Integer id){
        System.out.println(id);
        ModelAndView modelAndView = new ModelAndView();
        modelAndView.setViewName("list.jsp");
        modelAndView.addObject("id",id);
        return modelAndView;
    }

    // @RequestMapping(value = "/add",method = RequestMethod.POST)
    @PostMapping("/add")
    public String add(HttpServletRequest request,Model model,
                      @Valid SysUser sysUser, BindingResult bindingResult,
                      MultipartFile idPic,MultipartFile idPic2) throws IOException {

        if (bindingResult.hasErrors()){
            // 获取到所有的错误
            List<FieldError> fieldErrors = bindingResult.getFieldErrors();
            for (FieldError fieldError : fieldErrors) {
                // account  fieldError.getField()
                // 错误信息  fieldError.getDefaultMessage()
                model.addAttribute(fieldError.getField()+"Error",fieldError.getDefaultMessage());
            }

            return "add";
        }

        if (idPic != null){
            if (idPic.getSize()>2000000){
                model.addAttribute("idPicError","文件超过2M不能上传");
                return "add";
            }

            // 自定义 文件名  abc.jpg
            String suffix = idPic.getOriginalFilename().substring(idPic.getOriginalFilename().lastIndexOf("."));

            if (".jpg.png".indexOf(suffix)==-1){
                model.addAttribute("idPicError","文件格式不正确，不能上传");
                return "add";
            }

            // 指定文件存储的目录
            String path = request.getSession().getServletContext().getRealPath("statics")+File.separator+"upload";  // ?
            String fileName = RandomUtils.nextInt(1000000)+"_pic"+suffix;
            File fileTo = new File(path+File.separator+fileName);
            //如果文件不存在就创建
            if (!fileTo.exists()){
                fileTo.mkdirs();
            }
            //核心代码： 将文件存储到指定位置
            idPic.transferTo(fileTo);

            sysUser.setIdpicpath(fileName);
        }



        int result =sysUserService.add(sysUser);

        if (result>0){
            return "redirect:tolist";
        }

        model.addAttribute("errorMsg","修改失败");

        return "forward:toupdate/"+sysUser.getId();
    }

    @PostMapping("/update")
    public String update(Model model,SysUser sysUser){

        int result =sysUserService.update(sysUser);

        if (result>0){
            return "redirect:tolist";
        }

        model.addAttribute("errorMsg","新增失败");

        return "update";
    }

    @GetMapping("/view/{userid}")
    public String view(Model model,@PathVariable("userid") Integer id){

        SysUser sysUser = sysUserService.selectById(id);

        model.addAttribute("sysUser",sysUser);

        return "view";
    }

    @GetMapping(value = "/view2/{userid}")
    @ResponseBody
    public Object view2(@PathVariable("userid") Integer id){

        SysUser sysUser = sysUserService.selectById(id);
        return sysUser;
    }

    @GetMapping("/delete/{id}")
    @ResponseBody
    public String delete(@PathVariable Integer id){

       int result = sysUserService.delete(id);

       return result>0 ? "1" : "0";
    }
}
